<template>
  <div class="page-content parking-detail">
    <!-- 页面标题和操作按钮 -->
    <div class="mb-6 flex justify-between items-center">
      <div>
        <h1 class="text-2xl font-bold">停车场详情</h1>
        <p class="text-gray-500 mt-2">查看停车场的详细信息和实时数据</p>
      </div>
      <div class="flex gap-2">
        <el-button type="primary" @click="editParkingLot">
          <el-icon>
            <Edit /> </el-icon
          >编辑停车场
        </el-button>
        <el-button @click="goBack">
          <el-icon>
            <Back /> </el-icon
          >返回
        </el-button>
      </div>
    </div>

    <el-skeleton :loading="isLoading" animated>
      <template #template>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
          <div class="md:col-span-2">
            <el-skeleton-item
              variant="image"
              style="width: 100%; height: 300px; border-radius: 4px"
            />
            <div class="flex space-x-2 mt-2">
              <el-skeleton-item
                variant="image"
                style="width: 80px; height: 80px; border-radius: 4px"
              />
              <el-skeleton-item
                variant="image"
                style="width: 80px; height: 80px; border-radius: 4px"
              />
              <el-skeleton-item
                variant="image"
                style="width: 80px; height: 80px; border-radius: 4px"
              />
            </div>
          </div>
          <div>
            <el-skeleton-item variant="h3" style="width: 50%" />
            <el-skeleton-item variant="text" style="margin-top: 16px; width: 80%" />
            <el-skeleton-item variant="text" style="margin-top: 16px; width: 60%" />
            <el-skeleton-item variant="text" style="margin-top: 16px; width: 100%" />
          </div>
        </div>
      </template>

      <template #default>
        <el-row :gutter="24">
          <!-- 左侧停车场信息 -->
          <el-col :md="16" :sm="24">
            <el-card shadow="hover" class="mb-6">
              <div class="parking-header flex justify-between items-start">
                <div>
                  <h2 class="text-xl font-semibold">{{ parkingLot.name }}</h2>
                  <div class="flex items-center mt-2">
                    <el-icon>
                      <Location />
                    </el-icon>
                    <span class="ml-2 text-gray-600">{{ parkingLot.location }}</span>
                  </div>
                </div>
                <el-tag :type="getStatusType(parkingLot.status)" size="large">
                  {{ parkingLot.status }}
                </el-tag>
              </div>

              <!-- 停车场图片 -->
              <div class="mt-4">
                <el-image
                  :src="parkingLot.imageUrl"
                  fit="cover"
                  style="width: 100%; height: 300px; border-radius: 8px"
                >
                  <template #error>
                    <div class="image-error-slot">
                      <el-icon>
                        <Picture />
                      </el-icon>
                    </div>
                  </template>
                </el-image>
              </div>

              <!-- 停车场描述 -->
              <div class="mt-6">
                <h3 class="text-lg font-medium mb-3">停车场介绍</h3>
                <p class="text-gray-700 leading-relaxed">{{ parkingLot.description }}</p>
              </div>
            </el-card>

            <!-- 车位使用情况 -->
            <el-card shadow="hover" class="mb-6">
              <template #header>
                <div class="flex justify-between items-center">
                  <span>车位使用情况</span>
                  <el-tag type="info">更新时间: {{ new Date().toLocaleTimeString() }}</el-tag>
                </div>
              </template>

              <div class="space-capacity">
                <div class="space-usage mb-6">
                  <el-progress
                    type="dashboard"
                    :percentage="getOccupancyPercentage(parkingLot)"
                    :color="getProgressColor(getOccupancyPercentage(parkingLot))"
                    :stroke-width="14"
                  >
                    <template #default>
                      <div class="text-center">
                        <div class="text-3xl font-bold">{{ parkingLot.availableSpaces }}</div>
                        <div class="text-sm text-gray-500">可用车位</div>
                      </div>
                    </template>
                  </el-progress>
                </div>

                <div class="capacity-stats grid grid-cols-3 gap-4">
                  <div class="stat-item text-center p-4 bg-blue-50 dark:bg-blue-900 rounded-lg">
                    <div class="text-2xl font-bold text-blue-500 dark:text-blue-300">{{
                      parkingLot.totalSpaces
                    }}</div>
                    <div class="text-sm text-gray-500 dark:text-gray-400">总车位</div>
                  </div>
                  <div class="stat-item text-center p-4 bg-red-50 dark:bg-red-900 rounded-lg">
                    <div class="text-2xl font-bold text-red-500 dark:text-red-300">{{
                      parkingLot.totalSpaces - parkingLot.availableSpaces
                    }}</div>
                    <div class="text-sm text-gray-500 dark:text-gray-400">已占用</div>
                  </div>
                  <div class="stat-item text-center p-4 bg-green-50 dark:bg-green-900 rounded-lg">
                    <div class="text-2xl font-bold text-green-500 dark:text-green-300"
                      >{{
                        Math.floor((parkingLot.availableSpaces / parkingLot.totalSpaces) * 100)
                      }}%</div
                    >
                    <div class="text-sm text-gray-500 dark:text-gray-400">空置率</div>
                  </div>
                </div>
              </div>
            </el-card>

            <!-- 收费标准 -->
            <el-card shadow="hover" class="mb-6">
              <template #header>
                <div class="flex justify-between items-center">
                  <span>收费标准</span>
                </div>
              </template>

              <div class="fee-table">
                <el-table :data="feeTable" border style="width: 100%">
                  <el-table-column prop="type" label="类型" width="120" />
                  <el-table-column prop="fee" label="费用" width="120" />
                  <el-table-column prop="description" label="说明" />
                </el-table>
              </div>
            </el-card>
          </el-col>

          <!-- 右侧信息栏 -->
          <el-col :md="8" :sm="24">
            <!-- 基本信息 -->
            <el-card shadow="hover" class="mb-6">
              <template #header>
                <div class="flex justify-between items-center">
                  <span>基本信息</span>
                </div>
              </template>

              <div class="basic-info space-y-4">
                <div class="info-item flex">
                  <span class="info-label text-gray-500 w-24">营业时间：</span>
                  <span class="info-value">{{ parkingLot.openingHours }}</span>
                </div>
                <div class="info-item flex">
                  <span class="info-label text-gray-500 w-24">联系电话：</span>
                  <span class="info-value">{{ parkingLot.contactPhone || '暂无数据' }}</span>
                </div>
                <div class="info-item flex">
                  <span class="info-label text-gray-500 w-24">创建时间：</span>
                  <span class="info-value">{{ formatDateTime(parkingLot.createTime) }}</span>
                </div>
                <div class="info-item flex">
                  <span class="info-label text-gray-500 w-24">更新时间：</span>
                  <span class="info-value">{{ formatDateTime(parkingLot.updateTime) }}</span>
                </div>
              </div>
            </el-card>

            <!-- 设施情况 -->
            <el-card shadow="hover" class="mb-6">
              <template #header>
                <div class="flex justify-between items-center">
                  <span>设施情况</span>
                </div>
              </template>

              <div class="facilities-tags">
                <el-tag
                  v-for="feature in parkingLot.features || defaultFeatures"
                  :key="feature"
                  class="mr-2 mb-2"
                  effect="light"
                >
                  {{ feature }}
                </el-tag>
              </div>
            </el-card>

            <!-- 流量统计 -->
            <el-card shadow="hover">
              <template #header>
                <div class="flex justify-between items-center">
                  <span>今日停车统计</span>
                </div>
              </template>

              <div class="traffic-stats">
                <div class="grid grid-cols-2 gap-4 mb-4">
                  <div class="stat-box text-center p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
                    <div class="text-xl font-bold">{{ trafficStats.todayEntries }}</div>
                    <div class="text-sm text-gray-500">今日入场</div>
                  </div>
                  <div class="stat-box text-center p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
                    <div class="text-xl font-bold">{{ trafficStats.todayExits }}</div>
                    <div class="text-sm text-gray-500">今日出场</div>
                  </div>
                  <div class="stat-box text-center p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
                    <div class="text-xl font-bold">{{ trafficStats.peakHour }}</div>
                    <div class="text-sm text-gray-500">高峰时段</div>
                  </div>
                  <div class="stat-box text-center p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
                    <div class="text-xl font-bold">¥{{ trafficStats.todayIncome }}</div>
                    <div class="text-sm text-gray-500">今日收入</div>
                  </div>
                </div>

                <div class="mt-4">
                  <div class="text-sm text-gray-500 mb-2">停车时长分布</div>
                  <el-progress
                    :percentage="20"
                    :color="'#409eff'"
                    :format="() => '< 1小时: 20%'"
                    class="mb-2"
                  />
                  <el-progress
                    :percentage="45"
                    :color="'#67c23a'"
                    :format="() => '1-3小时: 45%'"
                    class="mb-2"
                  />
                  <el-progress
                    :percentage="25"
                    :color="'#e6a23c'"
                    :format="() => '3-6小时: 25%'"
                    class="mb-2"
                  />
                  <el-progress :percentage="10" :color="'#f56c6c'" :format="() => '> 6小时: 10%'" />
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </template>
    </el-skeleton>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { Edit, Back, Picture, Location } from '@element-plus/icons-vue'
  import type { ParkingLotType } from '@/types/parking'
  import { ParkingLotStatus } from '@/types/parking'

  const route = useRoute()
  const router = useRouter()
  const parkingLotId = ref(route.query.id ? Number(route.query.id) : 0)
  const isLoading = ref(true)

  // 停车场信息
  const parkingLot = ref<ParkingLotType>({
    id: 0,
    name: '',
    location: '',
    totalSpaces: 0,
    availableSpaces: 0,
    status: '',
    fee: {
      hourly: 0,
      daily: 0
    },
    openingHours: ''
  })

  // 默认设施
  const defaultFeatures = ['照明系统', '视频监控', '消防设备', '电子计费', '无障碍通道']

  // 收费表格数据
  const feeTable = ref([
    {
      type: '小型车辆',
      fee: `¥${parkingLot.value.fee?.hourly || 0}/小时`,
      description: '最高封顶¥50/天'
    },
    {
      type: '大型车辆',
      fee: `¥${(parkingLot.value.fee?.hourly || 0) * 1.5}/小时`,
      description: '最高封顶¥80/天'
    },
    {
      type: '新能源车辆',
      fee: `¥${(parkingLot.value.fee?.hourly || 0) * 0.8}/小时`,
      description: '享受8折优惠'
    },
    {
      type: '月卡用户',
      fee: '¥300/月',
      description: '不限次数'
    }
  ])

  // 交通统计数据
  const trafficStats = ref({
    todayEntries: 0,
    todayExits: 0,
    peakHour: '',
    todayIncome: 0
  })

  // 获取状态标签类型
  const getStatusType = (status: string) => {
    switch (status) {
      case ParkingLotStatus.OPEN:
        return 'success'
      case ParkingLotStatus.FULL:
        return 'warning'
      case ParkingLotStatus.MAINTENANCE:
        return 'info'
      case ParkingLotStatus.CLOSED:
        return 'danger'
      default:
        return ''
    }
  }

  // 获取车位占用百分比
  const getOccupancyPercentage = (parkingLot: ParkingLotType): number => {
    if (parkingLot.totalSpaces === 0) return 0
    return Math.round(
      ((parkingLot.totalSpaces - parkingLot.availableSpaces) / parkingLot.totalSpaces) * 100
    )
  }

  // 根据占用百分比获取进度条颜色
  const getProgressColor = (percentage: number): string => {
    if (percentage >= 90) return '#F56C6C' // 红色
    if (percentage >= 70) return '#E6A23C' // 黄色
    return '#67C23A' // 绿色
  }

  // 格式化日期时间
  const formatDateTime = (dateStr?: string) => {
    if (!dateStr) return '暂无数据'
    return new Date(dateStr).toLocaleString()
  }

  // 获取停车场详情
  const getParkingLotDetail = async () => {
    isLoading.value = true

    try {
      // 模拟API请求
      setTimeout(() => {
        // 这里应该是从API获取数据，这里使用模拟数据
        parkingLot.value = {
          id: parkingLotId.value,
          name: '东门停车场',
          location: '景区东门入口处',
          totalSpaces: 200,
          availableSpaces: 45,
          status: ParkingLotStatus.OPEN,
          fee: {
            hourly: 10,
            daily: 50
          },
          openingHours: '24小时开放',
          imageUrl: `https://picsum.photos/800/400?random=${parkingLotId.value}`,
          description:
            '东门停车场位于景区东门入口处，交通便利，设施完善。停车场共有200个车位，包括普通车位、残疾人专用车位和新能源车专用充电车位。停车场采用自动化管理系统，配备高清监控和照明设施，确保车辆安全。',
          features: [
            '视频监控',
            '24小时值守',
            '自动计费',
            '充电桩',
            '无障碍设施',
            '消防设备',
            '照明系统'
          ],
          contactPhone: '0755-12345678',
          createTime: '2023-01-01 00:00:00',
          updateTime: '2023-06-15 10:30:00'
        }

        // 更新收费表格数据
        feeTable.value = [
          {
            type: '小型车辆',
            fee: `¥${parkingLot.value.fee.hourly}/小时`,
            description: `最高封顶¥${parkingLot.value.fee.daily}/天`
          },
          {
            type: '大型车辆',
            fee: `¥${parkingLot.value.fee.hourly * 1.5}/小时`,
            description: `最高封顶¥${parkingLot.value.fee.daily * 1.5}/天`
          },
          {
            type: '新能源车辆',
            fee: `¥${parkingLot.value.fee.hourly * 0.8}/小时`,
            description: '享受8折优惠'
          },
          {
            type: '月卡用户',
            fee: '¥300/月',
            description: '不限次数'
          }
        ]

        // 生成模拟交通统计数据
        trafficStats.value = {
          todayEntries: Math.floor(Math.random() * 500) + 100,
          todayExits: Math.floor(Math.random() * 400) + 50,
          peakHour: '10:00-12:00',
          todayIncome: Math.floor(Math.random() * 5000) + 1000
        }

        isLoading.value = false
      }, 1000)

      // 实际API调用示例:
      // const res = await parkingService.getParkingLotDetail(parkingLotId.value)
      // if (res.code === 200) {
      //   parkingLot.value = res.data
      //   isLoading.value = false
      // }
    } catch (error) {
      console.error('获取停车场详情失败', error)
      isLoading.value = false
    }
  }

  // 编辑停车场
  const editParkingLot = () => {
    router.push({
      path: '/parking/edit',
      query: { id: parkingLotId.value }
    })
  }

  // 返回列表
  const goBack = () => {
    router.push('/parking/ParkingList')
  }

  onMounted(() => {
    getParkingLotDetail()
  })
</script>

<style lang="scss" scoped>
  .parking-detail {
    .image-error-slot {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 100%;
      background: var(--el-fill-color-light);
      color: var(--el-text-color-secondary);
      font-size: 30px;
    }
  }
</style>
